package models

import "fmt"

type Cd struct {
	Model
	CId          int    `gorm:"column:c_id" json:"c_id" form:"c_id"`
	BuildID      int    `gorm:"column:build_id" json:"build_id" form:"build_id"`
	GroupId      string `gorm:"column:group_id" json:"group_id" form:"group_id"`
	DeployResult string `gorm:"column:deploy_result" json:"deploy_result" form:"deploy_result"`
	Log          string `gorm:"column:log" json:"log" form:"log"`
}

func CreateCD(cd Cd) error {
	return db.Create(&cd).Error
}

func UpdateCD(cid int, cd Cd) error {
	return db.Where("c_id = ?", cid).Updates(&cd).Error
}

func UpdateOneCD(cid int, cd Cd) {
	if err := db.Where("c_id = ?", cid).Where("build_id = ?", cd.BuildID).Updates(&cd).Error; err != nil {
		fmt.Println("未找到， 更新总的")
		UpdateCD(cid, cd)
	}
}

func DeleteCD(cid int) error {
	return db.Where("c_id = ?", cid).Delete(&Cd{}).Error
}

func GetCD(cid int) Cd {
	cd := Cd{}
	db.Where("c_id = ?", cid).First(&cd)
	return cd
}

func GetLastCDByCID(cid int) Cd {
	cd := Cd{}
	db.Where("c_id = ?", cid).Last(&cd)
	return cd
}

func GetCdByBuildID(buildID int) Cd {
	cd := Cd{}
	db.Where("build_id = ?", buildID).First(&cd)
	return cd
}

func GetCDs(cd Cd) []Cd {
	cds := make([]Cd, 0)
	db.Where(&cd).Find(&cds)
	return cds
}

func AddCdLog(id int, result string, log string) error {
	sql := fmt.Sprintf(`UPDATE devops_cd  SET deploy_result = "%s", log = CONCAT(log, "%s") WHERE id = %d`, result, log, id)
	return db.Exec(sql).Error
}
